<template>
  <view class="profile-container">
    <!-- 安全区域顶部占位 -->
    <view
      class="safe-area-top"
      :style="{ height: safeAreaInsets.top + 'px' }"
    ></view>

    <!-- 页面主要内容 -->
    <view class="main-content">
      <!-- 顶部用户信息卡片 -->
      <view class="user-card" :style="currentGradient">
        <view class="avatar-section">
          <image
            :src="userInfo.avatar"
            mode="aspectFill"
            class="avatar-image"
          />
          <view class="user-info">
            <text class="login-text" @click="handleLoginClick">
              {{ isLogin ? userInfo.nickname : "点击登录" }}
            </text>
            <text class="user-type" v-if="isLogin">
              {{ getUserTypeText(userInfo.userType) }}
            </text>
          </view>
          <image
            v-if="isLogin"
            src="/static/icons/arrow-right.png"
            class="arrow-icon"
            @click="navigateTo('/pages/userEdit')"
          />
        </view>

        <view class="stats-section">
          <view class="stat-item">
            <text class="stat-value">{{ stats.trainingCount }}</text>
            <text class="stat-label">训练次数</text>
          </view>
          <view class="stat-item">
            <text class="stat-value">{{ stats.trainingDuration }}</text>
            <text class="stat-label">训练时长</text>
          </view>
        </view>
      </view>

      <!-- 功能区域 -->
      <view class="function-section">
        <view class="section-title" :style="currentGradient">
          <text class="section-title-text">会员专区</text>
        </view>
        <view class="function-list">
          <view
            v-for="(item, index) in functions"
            :key="index"
            class="function-item"
            @click="navigateTo(item.path)"
          >
            <view class="function-content">
              <text class="function-text">{{ item.name }}</text>
            </view>
            <image src="/static/icons/arrow-right.png" class="arrow-icon" />
          </view>
        </view>
      </view>

      <!-- 教师专区 -->
      <view
        class="function-section"
        v-if="
          isLogin && (userInfo.userType === '2' || userInfo.userType === '3')
        "
      >
        <view class="section-title" :style="currentGradient">
          <text class="section-title-text">教师专区</text>
        </view>
        <view class="function-list">
          <view
            v-for="(item, index) in teacher_functions"
            :key="index"
            class="function-item"
            @click="navigateTo(item.path)"
          >
            <view class="function-content">
              <text class="function-text">{{ item.name }}</text>
            </view>
            <image src="/static/icons/arrow-right.png" class="arrow-icon" />
          </view>
        </view>
      </view>

      <!-- 主题切换 -->
      <view class="function-section">
        <view class="section-title" :style="currentGradient">
          <text class="section-title-text">设置</text>
        </view>
        <view class="function-list">
          <view class="function-item" @click="showThemePicker = true">
            <view class="function-content">
              <text class="function-text">切换主题</text>
            </view>
            <image src="/static/icons/arrow-right.png" class="arrow-icon" />
          </view>

          <!-- 退出登录按钮 (移到设置区域内部) -->
          <view class="function-item" v-if="isLogin" @click="logout">
            <view class="function-content">
              <text class="function-text logout-text">退出登录</text>
            </view>
            <image src="/static/icons/arrow-right.png" class="arrow-icon" />
          </view>
        </view>
      </view>

      <!-- 主题选择弹窗 -->
      <view
        class="theme-picker-popup"
        v-if="showThemePicker"
        @click="showThemePicker = false"
      >
        <view class="popup-content" @click.stop>
          <view class="popup-header">
            <text class="popup-text">选择主题</text>
            <view class="close-btn" @click.stop="showThemePicker = false"
              >×</view
            >
          </view>

          <view class="theme-list">
            <view
              v-for="(theme, key) in allThemes"
              :key="key"
              class="theme-item"
              @click="switchToTheme(key)"
            >
              <view
                class="theme-preview"
                :style="getThemePreviewStyle(theme)"
              ></view>
              <text class="theme-name">{{ theme.name }}</text>
              <view class="checkmark" v-if="currentThemeKey === key">✓</view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部弹窗 -->
      <view
        class="bottom-popup"
        v-if="showBottomPopupFlag"
        @click="closeBottomPopup"
      >
        <view class="popup-content" @click.stop>
          <view class="popup-header">
            <text class="popup-text">登录查看课程信息</text>
            <view class="close-btn" @click.stop="closeBottomPopup">×</view>
          </view>

          <!-- 微信获取手机号按钮 -->
          <button
            class="popup-btn"
            :style="currentGradient"
            open-type="getPhoneNumber"
            @getphonenumber="onGetPhoneNumber"
            @click="closeBottomPopupImmediately"
          >
            微信一键登录
          </button>
          <text class="popup-subtext">我们承诺保护您的隐私信息</text>
        </view>
      </view>
    </view>

    <!-- 安全区域底部占位 -->
    <view
      class="safe-area-bottom"
      :style="{ height: safeAreaInsets.bottom + 'px' }"
    ></view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { onShow } from "@dcloudio/uni-app";
import { register, getUserProfile, logoutApi } from "@/api/userApi";
import { navigateTo } from "@/utils/router";
import { getCurrentTheme, getAllThemes, switchTheme } from "@/utils/theme";

// 安全区域边距
const safeAreaInsets = ref({
  top: 0,
  bottom: 0,
});

// 获取安全区域信息
const getSafeAreaInsets = () => {
  try {
    const systemInfo = uni.getSystemInfoSync();
    console.log("完整系统信息:", JSON.stringify(systemInfo));

    // 尝试获取安全区域信息（在支持的平台上）
    if (systemInfo.safeArea) {
      console.log("安全区域信息:", JSON.stringify(systemInfo.safeArea));
      console.log("窗口高度:", systemInfo.windowHeight);

      safeAreaInsets.value.top = systemInfo.safeArea.top;
      safeAreaInsets.value.bottom =
        systemInfo.windowHeight - systemInfo.safeArea.bottom;

      console.log(
        "计算后的安全区域 - 顶部:",
        safeAreaInsets.value.top,
        "底部:",
        safeAreaInsets.value.bottom
      );
    } else {
      console.log("平台不支持安全区域或未获取到安全区域信息");
      // 不支持安全区域的平台使用0值
      safeAreaInsets.value.top = 0;
      safeAreaInsets.value.bottom = 0;
    }
  } catch (e) {
    console.error("获取安全区域信息失败:", e);
    // 出错时使用默认值
    safeAreaInsets.value.top = 0;
    safeAreaInsets.value.bottom = 0;
  }
};

// 用户信息
const userInfo = ref({
  avatar: "/static/images/avatar.png",
  nickname: "游客",
  mobile: "",
  userType: "0",
});

// 登录状态
const isLogin = ref(false);

// 用户数据统计
const stats = ref({
  trainingCount: 0,
  trainingDuration: 0,
});

// 功能入口
const functions = ref([
  { name: "上课记录", path: "/pages/classRecord" },
  { name: "缴费记录", path: "/pages/paymentRecord" },
]);

// 教师功能入口
const teacher_functions = ref([
  { name: "授课打卡", path: "/pages/teacher/teacherAttendance" },
  { name: "授课记录", path: "/pages/teacher/teacherAttendanceRecord" },
]);

// 底部弹窗显示状态
const showBottomPopupFlag = ref(false);

// 主题选择弹窗显示状态
const showThemePicker = ref(false);

// 当前主题
const currentTheme = ref(getCurrentTheme());

// 获取所有主题
const allThemes = getAllThemes();

// 获取当前主题键名
const currentThemeKey = computed(() => {
  const themeKeys = Object.keys(allThemes);

  for (let key of themeKeys) {
    const themeConfig = allThemes[key];
    if (
      themeConfig.start === currentTheme.value.start &&
      themeConfig.end === currentTheme.value.end
    ) {
      return key;
    }
  }
  return "purple";
});

// 计算当前主题的渐变样式
const currentGradient = computed(() => {
  return `background: linear-gradient(135deg, ${currentTheme.value.start} 0%, ${currentTheme.value.end} 100%);`;
});

/**
 * 获取用户类型文本
 */
const getUserTypeText = (userType: string) => {
  const typeMap: Record<string, string> = {
    "0": "游客",
    "1": "学员",
    "2": "教师",
    "3": "学员/教师",
  };
  return typeMap[userType] || "未知身份";
};

/**
 * 检查登录状态
 */
const checkLoginStatus = async () => {
  try {
    const storedUserInfo = uni.getStorageSync("userInfo");
    const token = uni.getStorageSync("token");

    if (token && storedUserInfo) {
      // 用户已登录
      userInfo.value = {
        ...storedUserInfo,
        avatar: storedUserInfo.avatar || "/static/images/avatar.png",
      };
      isLogin.value = true;
      stats.value.trainingCount = storedUserInfo.trainingCount || 0;
      stats.value.trainingDuration = storedUserInfo.trainingDuration || 0;
    } else {
      // 用户未登录
      isLogin.value = false;
    }
  } catch (e) {
    console.error("检查登录状态失败:", e);
    isLogin.value = false;
  }
};

/**
 * 处理登录点击事件
 */
const handleLoginClick = () => {
  if (!isLogin.value) {
    showBottomPopupFlag.value = true;
  }
};

/**
 * 显示底部弹窗
 */
const showBottomPopup = () => {
  if (isLogin.value) return;
  showBottomPopupFlag.value = true;
};

/**
 * 关闭底部弹窗
 */
const closeBottomPopup = () => {
  showBottomPopupFlag.value = false;
};

/**
 * 立即关闭底部弹窗
 */
const closeBottomPopupImmediately = () => {
  showBottomPopupFlag.value = false;
};

/**
 * 微信获取手机号回调
 */
const onGetPhoneNumber = async (res: any) => {
  if (res.detail.errMsg !== "getPhoneNumber:ok") {
    uni.showToast({ title: "获取手机号失败", icon: "none" });
    console.error("获取手机号失败:", res.detail.errMsg);
    return;
  }

  try {
    const phoneCode = res.detail.code;
    // 微信登录
    const loginRes = await new Promise<any>((resolve, reject) => {
      uni.login({
        provider: "weixin",
        success: resolve,
        fail: reject,
      });
    });

    console.log("微信登录凭证:", loginRes);
    const loginCode = loginRes.code;

    // 注册流程
    const registerRes = await register(loginCode, phoneCode);
    console.log("注册结果:", registerRes);

    if (registerRes.code !== 0) {
      uni.showToast({ title: registerRes.msg, icon: "none" });
      return;
    }

    //存储 token
    uni.setStorageSync("token", registerRes.data.accessToken);

    // 注册成功，更新用户信息
    const userProfileRes = await getUserProfile();
    console.log("用户信息:", userProfileRes);

    if (userProfileRes.code !== 0) {
      uni.showToast({ title: userProfileRes.msg, icon: "none" });
      return;
    }

    const userProfile = userProfileRes.data;

    // 更新用户信息
    userInfo.value = {
      ...userProfile,
      avatar: userProfile.avatar || "/static/images/avatar.png",
      nickname: userProfile.nickname || "微信用户",
    };

    isLogin.value = true;
    stats.value.trainingCount = userProfile.trainingCount || 0;
    stats.value.trainingDuration = userProfile.trainingDuration || 0;

    //  和 userInfo 到本地存储
    uni.setStorageSync("userInfo", userProfile);

    // 关闭弹窗
    showBottomPopupFlag.value = false;
  } catch (err) {
    console.error("登录注册失败:", err);
    uni.showToast({ title: "登录注册失败", icon: "none" });
  }
};

/**
 * 退出登录
 */
const logout = async () => {
  try {
    // 调用服务端登出接口
    try {
      await logoutApi();
    } catch (apiError) {
      console.warn("服务端登出接口调用失败:", apiError);
      // 即使服务端登出失败，也要执行客户端登出操作
    }

    // 客户端清除本地存储
    uni.removeStorageSync("token");
    uni.removeStorageSync("userInfo");
    isLogin.value = false;
    stats.value.trainingCount = 0;
    stats.value.trainingDuration = 0;

    // 重置用户信息
    userInfo.value = {
      avatar: "/static/images/avatar.png",
      nickname: "游客",
      mobile: "",
      userType: "0",
    };

    uni.showToast({ title: "已退出登录", icon: "none" });
  } catch (e) {
    console.error("退出登录失败:", e);
  }
};

/**
 * 获取主题预览样式
 */
const getThemePreviewStyle = (theme) => {
  return `background: linear-gradient(135deg, ${theme.start} 0%, ${theme.end} 100%);`;
};

/**
 * 切换主题
 */
const switchToTheme = (themeKey) => {
  if (switchTheme(themeKey)) {
    // 更新当前主题
    currentTheme.value = getCurrentTheme();

    // 关闭弹窗
    showThemePicker.value = false;

    uni.showToast({
      title: "主题切换成功",
      icon: "none",
    });
  }
};

// 页面加载时检查登录状态
onShow(() => {
  checkLoginStatus();
  // 每次页面显示时更新主题（确保切换后能正确显示）
  currentTheme.value = getCurrentTheme();
});

// 组件挂载时获取安全区域信息
onMounted(() => {
  getSafeAreaInsets();
});
</script>

<style scoped lang="scss">
.profile-container {
  min-height: 100vh;
  background-color: $background-color;
  display: flex;
  flex-direction: column;
}

/* 安全区域占位样式 */
.safe-area-top {
  width: 100%;
  background-color: transparent;
}

.safe-area-bottom {
  width: 100%;
  background-color: transparent;
}

.main-content {
  flex: 1;
  padding-left: 20rpx;
  padding-right: 20rpx;
}

/* 用户卡片 */
.user-card {
  margin-left: 20rpx;
  margin-right: 20rpx;
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.25);

  .avatar-section {
    display: flex;
    align-items: center;
    margin-bottom: 30rpx;

    .avatar-image {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-right: 20rpx;
      border: 3px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    }

    .user-info {
      flex: 1;
      display: flex;
      flex-direction: column;

      .login-text {
        font-size: 36rpx;
        font-weight: bold;
        color: $uni-text-color-inverse;
        margin-bottom: 10rpx;
      }

      .user-type {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.9);
        background: rgba(255, 255, 255, 0.2);
        padding: 6rpx 20rpx;
        border-radius: 20rpx;
        align-self: flex-start;
      }
    }

    .arrow-icon {
      width: 36rpx;
      height: 36rpx;
      opacity: 0.8;
      margin-left: 10rpx;
    }
  }

  .stats-section {
    display: flex;
    justify-content: space-around;
    background: rgba(255, 255, 255, 0.15);
    padding: 30rpx 0;
    border-radius: 16rpx;
    margin-top: 20rpx;

    .stat-item {
      text-align: center;
      flex: 1;

      .stat-label {
        font-size: 26rpx;
        color: rgba(255, 255, 255, 0.9);
        margin-bottom: 10rpx;
      }

      .stat-value {
        font-size: 40rpx;
        font-weight: bold;
        color: $uni-text-color-inverse;
      }
    }
  }
}

/* 功能区域 */
.function-section {
  margin-top: 40rpx;
  margin-left: 20rpx;
  margin-right: 20rpx;
  background: $uni-bg-color;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);

  .section-title {
    padding: 25rpx 30rpx;
    position: relative;

    .section-title-text {
      color: $uni-text-color-inverse;
      font-size: 32rpx;
      font-weight: bold;
    }

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 30rpx;
      right: 30rpx;
      height: 1rpx;
      background: rgba(255, 255, 255, 0.3);
    }
  }

  .function-list {
    .function-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 35rpx 30rpx;
      border-bottom: 1rpx solid $uni-border-color;
      transition: all 0.2s ease;

      &:last-child {
        border-bottom: none;
      }

      &:active {
        background-color: #f8f8f8;
        transform: translateX(5rpx);
      }

      .function-content {
        display: flex;
        align-items: center;

        .function-text {
          font-size: 32rpx;
          color: $uni-text-color;
          margin-left: 0;
        }

        .logout-text {
          color: #e53935;
          font-weight: 500;
        }
      }

      .arrow-icon {
        width: 28rpx;
        height: 28rpx;
        opacity: 0.5;
      }
    }
  }
}

/* 主题选择弹窗 */
.theme-picker-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;

  .popup-content {
    background: $uni-bg-color;
    border-radius: 20rpx;
    width: 80%;
    max-width: 500rpx;
    animation: slideUp 0.3s ease-out;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 30rpx;
      border-bottom: 1rpx solid $uni-border-color;

      .popup-text {
        font-size: 34rpx;
        color: $uni-text-color;
        font-weight: bold;
        flex: 1;
        text-align: center;
      }

      .close-btn {
        font-size: 40rpx;
        color: $uni-text-color-grey;
        width: 50rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: background-color 0.3s;

        &:active {
          background-color: #f0f0f0;
        }
      }
    }

    .theme-list {
      padding: 20rpx 30rpx 40rpx;

      .theme-item {
        display: flex;
        align-items: center;
        padding: 20rpx;
        margin-bottom: 20rpx;
        border-radius: 12rpx;
        background: #f8f9fa;
        transition: all 0.2s;

        &:last-child {
          margin-bottom: 0;
        }

        &:active {
          transform: translateY(-2rpx);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        .theme-preview {
          width: 60rpx;
          height: 60rpx;
          border-radius: 12rpx;
          margin-right: 20rpx;
        }

        .theme-name {
          flex: 1;
          font-size: 30rpx;
          color: $uni-text-color;
        }

        .checkmark {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          background: #4caf50;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: bold;
        }
      }
    }
  }
}

/* 底部弹窗 */
.bottom-popup {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 999;

  .popup-content {
    background: $uni-bg-color;
    padding: 50rpx 40rpx;
    border-radius: 20rpx 20rpx 0 0;
    text-align: center;
    width: 100%;
    animation: slideUp 0.3s ease-out;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.15);

    .popup-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 40rpx;

      .popup-text {
        font-size: 34rpx;
        color: $uni-text-color;
        font-weight: bold;
        flex: 1;
        text-align: center;
      }

      .close-btn {
        font-size: 40rpx;
        color: $uni-text-color-grey;
        width: 50rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        border-radius: 50%;
        transition: background-color 0.3s;

        &:active {
          background-color: #f0f0f0;
        }
      }
    }

    .popup-btn {
      color: $uni-text-color-inverse;
      border-radius: 50rpx;
      padding: 30rpx 0;
      font-size: 34rpx;
      margin-bottom: 20rpx;
      font-weight: bold;
      border: none;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);

      &:active {
        transform: translateY(2rpx);
        box-shadow: 0 2px 6px rgba(102, 126, 234, 0.3);
      }
    }

    .popup-subtext {
      font-size: 24rpx;
      color: $uni-text-color-grey;
    }
  }
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
    opacity: 0.8;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
